const app = getApp()
import { sendMessageCode, saveFile, postSupplierAuth, postPersonAuth } from '../../../api/index'
const uploadOss = require('../../../utils/upload/uploadImg.js')
import { uuid } from '../../../utils/util'
let timer = null

Page({
  data: {
    isApprove: '',
    companyName: '',
    userInfo: {},
    form: {},
    showTypePopup: false,
    showStylePopup: false,
    showCatePopup: false,
    companyTypeStr: '',
    styleStr: '',
    mainBusinessStr:'',
    business: [],
    logoFiles: [],
    certificate: []
  },
  showTypeModal () {
    this.setData({ showTypePopup: true })
  },
  changeTypes ({ detail }) {
    this.setData({ 'form.companyType': detail.value, companyTypeStr: detail.label, showTypePopup: false })
  },
  closeTypePopup () {
    this.setData({ showTypePopup: false })
  },
  showStyleModal () {
    this.setData({ showStylePopup: true })
  },
  changeStyle ({ detail }) {
    let style = []
    let styleStr = []
    detail.forEach(item => {
      style.push(item.styleId)
      styleStr.push(item.styleName)
    })

    this.setData({ 'form.style': style.join(','), styleStr:styleStr.join(','), showStylePopup: false })
  },
  closeStylePopup () {
    this.setData({ showStylePopup: false })
  },
  showCateModal () {
    this.setData({ showCatePopup: true })
  },
  changeCate ({ detail }) {
    let mainBusiness = []
    let mainBusinessStr = []
    detail.forEach(item => {
      mainBusiness.push(item.classificationId)
      mainBusinessStr.push(item.classificationName)
    })

    this.setData({ 'form.mainBusiness': mainBusiness.join(','), mainBusinessStr:mainBusinessStr.join(','), showCatePopup: false })
  },
  closeCatePopup () {
    this.setData({ showCatePopup: false })
  },
  changeInput ({ currentTarget: { dataset: { key } }, detail }) {
    this.setData({ ['form.'+ key]: detail.value })
  },
  codeTimer () {
    this.setData({ time: 60 })
    timer = setInterval(() => {
      this.data.time--
      this.setData({ time: this.data.time })
      if (this.data.time <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  },
  async sendCode () {
    try {
      let reg = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/
      if (this.data.time > 0 && this.isSendCode) {
        return
      }
      if (!this.data.userInfo.mobile || !reg.test(this.data.userInfo.mobile)) {
        wx.showToast({ title: '请输入正确的手机号！', icon: 'none' })
        return
      }
      this.isSendCode = true
      await sendMessageCode({ mobile: this.data.userInfo.mobile })
      this.isSendCode = false
      await this.codeTimer()
      wx.showToast({ title: '短信验证码已发送', icon: 'none' })
    } catch (err) {
      this.isSendCode = false
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  deleteFile ({ currentTarget: { dataset: { index, key } } }) {
    this.data.form[`${key}`].splice(index, 1)
    this.setData({
      ['form.' + key]: this.data.form[key]
    })
  },
  deleteTempFile ({ currentTarget: { dataset: { index, key } } }) {
    this.data[`${key}`].splice(index, 1)
    this.setData({
      [`${key}`]: this.data[key]
    })
  },
  addFile ({ target: { dataset: { key, num } } }) {
    let _this = this
    if (parseInt(num) - this.data.form[key].length === 0) {
      wx.showToast({ title: `最多只能上传${num}图片！`, icon: 'none' })
      return
    }
    wx.chooseMedia({
      count: parseInt(num),
      mediaType: ['image'],
      async success (res) {
        res.tempFiles.forEach(item => {
          item.uuid = uuid()
          item.progress = 0
        })
        _this.data[`${key}`].push(...res.tempFiles)
        _this.setData({
          [`${key}`]: _this.data[`${key}`]
        })
        let tempFiles = _this.data[`${key}`]
        let temFileList = []
        if (tempFiles.length) {
          temFileList = await Promise.all(tempFiles.map(async (item, index) => {
            const { fileUrl, fileName } = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
            if (fileUrl) {
              const { ResultSet } = await saveFile({
                fileList: [{
                  fileSize: item.size,
                  fileName: fileName,
                  fileUrl: fileUrl
                }]
              })
              return {
                uuid: item.uuid,
                fileId: ResultSet.userData.fileIdList[0].fileId,
                fileName: fileName,
                fileUrl: ResultSet.userData.fileIdList[0].fileUrl
              }
            } else {
              tempFiles[index].success = 1
              _this.setData({
                [`${key}`]: tempFiles
              })
            }
          }))
        }
        let tempFileList = temFileList.filter(item => item)
        _this.data.form[key].push(...tempFileList)
        _this.data.form[key].forEach((item) => {
          let rowIndex = tempFiles.findIndex(row => row.uuid === item.uuid)
          if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
        })
        _this.setData({
          [`${key}`]: tempFiles,
          [`form.${key}`]: _this.data.form[key]
        })
      }
    })
  },
  uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (res) => {
          resolve(res)
        },
        (err) => {
          resolve()
        },
        files, index, that, dataKey
      )
    })
  },
  async submit () {
    try {
      if (parseInt(this.data.isApprove) === 1) {
        if (!this.data.form.companyType) {
          wx.showToast({ title: '请选择企业性质！', icon: 'none' })
          return
        }
        if (!this.data.form.style) {
          wx.showToast({ title: '请选择企业类型！', icon: 'none' })
          return
        }
        if (!this.data.form.mainBusiness) {
          wx.showToast({ title: '请选择主营产品！', icon: 'none' })
          return
        }
        if (!this.data.form.personsInChargeOfCompany) {
          wx.showToast({ title: '请输入企业联系人！', icon: 'none' })
          return
        }
        if (!this.data.form.msgCode) {
          wx.showToast({ title: '请输入验证码！', icon: 'none' })
          return
        }
        if (this.data.form.business.length) {
          this.data.form.manufacturerBusinessLicense = this.data.form.business[0].fileId
        } else {
          wx.showToast({ title: '请上传营业执照！', icon: 'none' })
          return
        }
        if (this.data.form.logoFiles.length) {
          this.data.form.companyLogo = this.data.form.logoFiles[0].fileId
        } else {
          wx.showToast({ title: '请上企业logo！', icon: 'none' })
          return
        }
        if (this.data.form.certificate.length) {
          let fileList = []
          this.data.form.certificate.forEach(item => {
            fileList.push({
              qualificationName: item.fileName,
              qualificationFileId: item.fileId
            })
          })
          this.data.form.supplierAuthQualification = fileList
        } else {
          wx.showToast({ title: '请上其他证书！', icon: 'none' })
          return
        }
        await postSupplierAuth({ ...this.data.form })
        wx.showToast({ title: '企业认证提交成功！', icon: 'none' })
        wx.$nav.switchTab('/pages/account/index/index')
      } else {
        if (!this.data.form.realName) {
          wx.showToast({ title: '请输入姓名！', icon: 'none' })
          return
        }
        if (!this.data.form.email) {
          wx.showToast({ title: '请输入邮箱！', icon: 'none' })
          return
        }
        if (!this.data.form.msgCode) {
          wx.showToast({ title: '请输入验证码！', icon: 'none' })
          return
        }
        await postPersonAuth({ ...this.data.form })
        wx.showToast({ title: '企业认证提交成功！', icon: 'none' })
        wx.$nav.switchTab('/pages/account/index/index')
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ isApprove, companyName, supplierId }) {
    let form = {}
    const { userInfo } = app.globalData
    if (parseInt(isApprove) === 1) {
      form = {
        companyName: companyName,
        companyType: '',
        style: '',
        mainBusiness: '',
        personsInChargeOfCompany: '',
        personsInChargeOfCompanyPhone: userInfo.mobile,
        msgCode: '',
        manufacturerBusinessLicense: '',
        companyLogo: '',
        supplierAuthQualification: [],
        business: [],
        logoFiles: [],
        certificate: []
      }
    } else {
      form = {
        supplierId: supplierId,
        companyName: companyName,
        realName: '',
        mobile: userInfo.mobile,
        email: '',
        msgCode: ''
      }
    }
    this.setData({ isApprove, userInfo, form: form })
  }
})